package dmwr.repo.gae;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import dmwr.bean.Application;
import dmwr.repo.ApplicationRepo;

public class ApplicationRepoGae implements ApplicationRepo {
	private static final String KIND = "Application";
	private static final String NAME = "dmwr";
	private static final String PROPERTY_ENTRY_COUNT = "entryCount";

	@Override
	public Application get() {
		Application application = byName(NAME);
		if (application == null) {
			application = new Application(null, NAME, 0L);
			save(application);
		}
		return application;
	}

	@Override
	public Application byId(Long id) {
		return byKey(KeyFactory.createKey(KIND, id));
	}

	@Override
	public Application byName(String name) {
		return byKey(KeyFactory.createKey(KIND, name));
	}

	@Override
	public void save(Application application) {
		Entity entity = new Entity(KIND, NAME);
		entity.setProperty(PROPERTY_ENTRY_COUNT, application.getEntryCount());
		Gae.datastoreService().put(entity);
		if (application.getId() == null) {
			application.setId(entity.getKey().getId());
		}
	}

	private Application byKey(Key key) {
		try {
			return application(Gae.datastoreService().get(key));
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

	private Application application(Entity entity) {
		return new Application(entity.getKey().getId(), entity.getKey()
				.getName(), (Long) entity.getProperty(PROPERTY_ENTRY_COUNT));
	}
}
